/*
 * @lc app=leetcode.cn id=234 lang=cpp
 *
 * [234] 回文链表
 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <stdlib>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <cmath>

using namespace std;
// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* halfList(ListNode* head) {
        //快慢指针寻找中间节点的方法：快指针每次前进两个，慢指针每次前进一个
        //如1-2-3 快指针到3，慢指针到2，或1-2-3-4，快指针到3，慢指针到2
        //1-2-3-4-5，快指针3-5，慢指针23
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* curr = head;
        while (curr != nullptr) {
            ListNode* nextTemp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
    bool isPalindrome(ListNode* head) {
        if (head == nullptr) {
           return true;
        }
        //找到链表的一半后，翻转后面的部分
        ListNode* halfNode = halfList(head);
        ListNode* endNode = reverseList(halfNode->next);
        ListNode* p1 = head;
        ListNode* p2 = endNode;
        while (p2 != nullptr) {
            if (p1->val != p2->val) {
                return false;
            }
            p1 = p1->next;
            p2 = p2->next;
        }
        return true;
    }
};


// @lc code=end

//空间复杂度是O()
//  vector<int> vals;
// while (head) {
//     vals.emplace_back(head->val);
//     head = head->next;
// }
// for (int i = 0, j = (int)vals.size() - 1; i < j; ++i, --j) {
//     if (vals[i] != vals[j]) {
//         return false;
//     }
// }
// return true;
